package functionality;

import java.io.*;
import java.net.*;

import datalay.NetworkData;

public class Network {
	
	private static Network network = null;
	private NetworkData netData;
	private Socket client;
	
	private Network(){
		netData = new NetworkData();
	}

	public static Network getInstance(){
		if(network==null){
			network = new Network();
		}
		return network;
	}
	
	public void close() throws IOException{
		client.close();
	}
	
	public void connectToServer(String ip, int port) throws IOException{
		netData.setIPAddress(ip);
		netData.setPort(port);
		client = new Socket(netData.getIPAddress(), netData.getPort());
	}
	
	public void sendToServer(String message) throws UnknownHostException
	   {
		if(client == null)
			return;
		try{			
			OutputStream outToServer = client.getOutputStream();
			DataOutputStream out = new DataOutputStream(outToServer);
			
			out.writeBytes(message + "\r\n");
			
	      }	catch(IOException e)
	      {
	         e.printStackTrace();
	      }
	   }
	
	public String readFromServer() throws UnknownHostException 
		{
		if(client == null)
			return "NO CONNECTION";
		
		try {
			BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));

			String sentenceFromServer = inFromServer.readLine();
			
			return sentenceFromServer;
			
		} catch (IOException e) {
			e.printStackTrace();
		}

		
		return "";
		}
}

